//
//  YJYCarouselView.m
//  BannerViewDemo
//
//  Created by BaizYi on 2019/1/8.
//  Copyright © 2019 BaizYi. All rights reserved.
//

#import "YJYCarouselView.h"
#import "YJYVideoView.h"

@interface YJYCarouselView ()<UIScrollViewDelegate>

@property(strong,nonatomic) UIScrollView  *scrollView;
@property(strong,nonatomic) UIPageControl  *pageControl;
@property(strong,nonatomic) YJYVideoView  *videoView;


@end


@implementation YJYCarouselView

-(instancetype)scrollViewFrame:(CGRect)frame imageArray:(NSArray *)imageArray{
    YJYCarouselView *carouselView = [[YJYCarouselView alloc]initWithFrame:frame];
    carouselView.contentArray = imageArray;
    return carouselView;
}

-(void)setContentArray:(NSArray *)contentArray{
    _contentArray = contentArray;
    [self configUI];
}

-(void)configUI{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.scrollView.contentSize = CGSizeMake(self.contentArray.count * self.frame.size.width, self.frame.size.height);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    [self addSubview:self.scrollView];
    
    for (NSInteger i=0; i<self.contentArray.count; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
        imageView.userInteractionEnabled = YES;
        imageView.image = [UIImage imageNamed:self.contentArray[i]];
        if (i == 0) {
            self.videoView = [YJYVideoView videoViewFrame:imageView.frame videoUrl:self.contentArray[i]];
            [self.scrollView addSubview:self.videoView];
        }else{
            [self.scrollView addSubview:imageView];
        }
    }
    self.pageControl = [[UIPageControl alloc]init];
    self.pageControl.frame = CGRectMake(0, self.frame.size.height - 30, self.frame.size.width, 30);
    self.pageControl.numberOfPages = self.contentArray.count;
    self.pageControl.currentPage = 0;
    self.pageControl.enabled = NO;
    self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    [self addSubview:self.pageControl];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger currentPage = round(scrollView.contentOffset.x / self.frame.size.width);
    self.pageControl.currentPage = currentPage;
    if (self.videoView.isPlay) {
        if (currentPage == 0) {
            [self.videoView start];
        }else{ 
            [self.videoView stop];
        }
    }
}



@end
